package com.example.demo004.service;

import com.example.demo004.User;
import java.util.*;

import javax.validation.Valid;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.*;

@Data
@AllArgsConstructor
@NoArgsConstructor
class Response {

    private int code;
    private String msg;
    private Object data;

    Response(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}

@Api(tags = "用戶管理")
@RestController
@CrossOrigin("*")
@RequestMapping(value = "/api/users")

public class UserControl {

    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());

    @GetMapping("/all")
    @ApiOperation("獲取用戶列表")
    public Response getlist() {

        return new Response(200, "msg", new ArrayList<User>(users.values()));

    }

    @PostMapping("/add")
    @ApiOperation(value = "添加一個用戶")
    public String postUser(@Valid @RequestBody User user) {
        // @RequestBody注解用来绑定通过http请求中application/json类型上传的数据
        users.put(user.getId(), user);
        System.out.println(user.getName());
        return "success";
    }

    @GetMapping("/{id}")
    public Response getUser(@PathVariable Long id) {

        return new Response(200, "msg", users.get(id));

        // url中的id可通过@PathVariable绑定到函数的参数中
        // return ;
    }

}
